package api

import (
	"context"
	"fmt"
	"github.com/lishimeng/go-log"
	"sync"
	"time"
)

var session = make(map[string]int64)
var lock sync.Mutex

var expireDuration = time.Hour * 20

func genSession() string {
	s := fmt.Sprintf("%d_%d", time.Now().UnixMilli(), time.Now().Day())
	lock.Lock()
	defer func() {
		lock.Unlock()
	}()
	session[s] = time.Now().UnixMilli()
	return s
}

// checkSession 检查session，过期返回false
func checkSession(s string) bool {
	now := time.Now().UnixMilli()
	if v, ok := session[s]; ok {
		return !_chkSessionExpired(now, v)
	} else {
		return false
	}

}

// _chkSessionExpired 是否过期， 过期返回true
func _chkSessionExpired(now int64, s int64) bool {
	return time.Duration(now-s) > expireDuration
}

func clearSession() {
	lock.Lock()
	defer func() {
		lock.Unlock()
	}()
	now := time.Now().UnixMilli()
	for k, v := range session {
		if _chkSessionExpired(now, v) {
			delete(session, k)
		}
	}
}

// ClearSession 定时清理任务
func ClearSession(ctx context.Context) (err error) {

	log.Info("Start clear session job")
	RunJob(ctx, time.Second*60*20, func() {
		defer func() {
			if e := recover(); e != nil {
				log.Info(e)
			}
		}()

		log.Info("Clear task")
		clearSession()
		return
	})
	return
}

type taskHandler func()

func RunJob(ctx context.Context, duration time.Duration, h taskHandler) {

	go func() {
		var timer = time.NewTimer(duration)
		defer func() {
			timer.Stop()
		}()
		for {
			select {
			case <-ctx.Done():
				return
			case <-timer.C:
				h()
				timer.Reset(duration)
			}
		}
	}()
}
